<template>
  <div></div>
</template>
<script>
import './jquery'
import { cleanCopy } from './util'

function compare(obj1, obj2) {
  var count = 0
  var keys = Object.keys(obj1)

  Object.keys(obj2).forEach(function (k) {
    if (keys.indexOf(k) < 0) {
      keys.push(k)
    }
  })
  keys.forEach(function (k) {
    if (JSON.stringify(obj1[k]) === JSON.stringify(obj2[k])) {
      ++count
    }
  })
  return count - keys.length
}

export default {
  name: 'FilteredSearchBox',
  props: {
    options: Object,
    value: Object
  },
  watch: {
    value: function (value) {
      this.setValue(value)
    },
    options: function (options) {
      this.searchBox.setFilters(options.filters)
    }
  },
  mounted: function () {
    var $searchBox
    var that = this

    $searchBox = $(that.$el).filteredSearchBox(that.options)
    that.searchBox = $searchBox.data('filteredsearchbox')
    that.setValue(that.value)
    that.searchBox.callback = function (data) {
      that.currentValue = that.getFullData(data)
      that.$emit('submit', cleanCopy(that.currentValue), that.searchBox)
    }
    $searchBox.on('change.fsb', function (e, data) {
      var fullData = that.getFullData(data)
      if (e.namespace === 'fsb' && compare(that.currentValue, fullData) !== 0) {
        that.currentValue = fullData
        that.$emit('input', cleanCopy(fullData), that.searchBox)
      }
    })
    that.searchBox.$input.on('blur', function () {
      that.$emit('blur', that.searchBox)
    })
  },
  created: function () {
    // 在这里定义 currentValue，避免被 Vue Observer 影响内容
    this.currentValue = {}
  },
  methods: {
    setValue: function (value) {
      var data

      if (!this.searchBox) {
        return
      }
      data = this.getFullData(value)
      if (compare(this.currentValue, data) !== 0) {
        this.currentValue = data
        this.searchBox.setData(cleanCopy(data))
      }
    },
    getFullData: function (data) {
      var fullData = {}

      if (typeof data !== 'object') {
        data = {}
      }
      ['search'].concat(this.searchBox.filters.map(function (f) {
        return f.key
      })).forEach(function (key) {
        var value = data[key]
        if (typeof value === 'undefined') {
          fullData[key] = ''
        } else if (typeof value === 'number') {
          fullData[key] = value.toString()
        } else {
          fullData[key] = value
        }
      })
      return cleanCopy(fullData)
    }
  }
}
</script>
